/*
 * Copyright 2010 Brian Watkins
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package bw.os;

import javax.cache.*;
import java.util.*;
import bw.util.*;
import com.google.appengine.api.memcache.stdimpl.GCacheFactory;
import com.google.appengine.api.memcache.MemcacheService;

public class GoogleMemCache implements MemoryCache
{
    private int _defaultTimeout;
    private Cache _cache = null;

    public GoogleMemCache ()
    {
        //no timeout 
        _defaultTimeout = -1;
    }

    public GoogleMemCache ( int timeout )
    {
        //default timeout is in seconds
        _defaultTimeout = timeout;
    }

    public void put ( String key, Object obj )
    {
        _cache.put( key, obj );
    }

    public Object get ( String key )
    {
        return _cache.get( key );
    }

    public Object remove ( String key )
    {
        return _cache.remove( key );
    }

    public void start () 
    {
        try
        {
            CacheFactory factory = CacheManager.getInstance().getCacheFactory();

            Map props = new HashMap();
            if ( _defaultTimeout > 0 )
            {
                props.put( GCacheFactory.EXPIRATION_DELTA, _defaultTimeout );
            }
            props.put( MemcacheService.SetPolicy.SET_ALWAYS, true );

            _cache = factory.createCache( props );

            Log.getInstance().write( "Google MemCache Initialized!" );
        }
        catch ( Exception ex )
        {
            Log.getInstance().write( "Problem creating cache!", ex );
        }
    }

    public void shutdown ()
    {
        //nothing
    }
}